package cn.tedu.eguser1.controller;

import cn.tedu.eguser1.base.response.JsonResult;
import cn.tedu.eguser1.base.response.StatusCode;
import cn.tedu.eguser1.mapper.UserMapper;
import cn.tedu.eguser1.pojo.dto.UserAddParam;
import cn.tedu.eguser1.pojo.dto.UserLoginParam;
import cn.tedu.eguser1.pojo.dto.UserUpdateParam;
import cn.tedu.eguser1.pojo.entity.User;
import cn.tedu.eguser1.pojo.vo.UserListVO;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.resource.ResourceUrlProvider;

import java.util.Date;
import java.util.List;

@Slf4j
@Validated
@RestController
@RequestMapping("/v1/user")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    /**
     * 1.添加用户功能
     */
    @PostMapping("/add")
    public JsonResult add(@RequestBody @Validated UserAddParam userAddParam){
        log.debug("userAddParam = " + userAddParam);
        User user = new User();
        BeanUtils.copyProperties(userAddParam, user);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        System.out.println("user = " + user);
        int i = userMapper.insertUser(user);
        if (i > 0){
            return JsonResult.ok();
        }
        return new JsonResult(StatusCode.OPERATION_FAILED);
    }

    /**
     * 2.查询用户列表功能
     */
    @GetMapping("/list")
    public JsonResult list(){
        List<UserListVO> userListVOS = userMapper.listUser();
        System.out.println("userListVOS = " + userListVOS);

        return JsonResult.ok(userListVOS);
    }

    /**
     * 3.删除指定用户功能
     */
    @PostMapping("/del/{id}")
    public JsonResult del(@PathVariable @Range(min = 1L, max = 100L, message = "用户id必须在1-100之间") Long id){
        log.debug("id = " + id);
        int i = userMapper.deleteUserById(id);
        if (i > 0){
            return JsonResult.ok();
        }
        return new JsonResult(StatusCode.OPERATION_FAILED);
    }

    /**
     * 4.更新指定用户功能
     */
    @PostMapping("/update")
    public JsonResult update(@RequestBody UserUpdateParam userUpdateParam){
        log.debug("userUpdateParam = " + userUpdateParam);
        User user = new User();
        BeanUtils.copyProperties(userUpdateParam, user);
        user.setUpdateTime(new Date());
        System.out.println("user = " + user);
        int i = userMapper.updateUserById(user);
        if (i > 0){
            return JsonResult.ok();
        }
        return new JsonResult(StatusCode.OPERATION_FAILED);
    }

    /**
     * 5.登录功能:
     */
    @PostMapping("/login")
    public JsonResult login(@RequestBody UserLoginParam userLoginParam){
        log.debug("userLoginParam = " + userLoginParam);
        return JsonResult.ok();
    }
}






